package com.spdzen.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spdzen.mapper.VideoCategoryMapper;
import com.spdzen.model.Video;
import com.spdzen.model.VideoCategory;
import com.spdzen.service.VideoCategoryService;
import com.spdzen.service.VideoService;
import com.spdzen.support.SimpleServiceImpl;
import com.spdzen.support.exception.ResultCodeException;
import com.spdzen.support.result.BizResultCode;
import com.spdzen.support.result.ResultCode;
import com.spdzen.vo.VideoCategoryAdminVO;

/**
 * 视频分类  服务实现类
 */
@Service("videoCategoryService")
public class VideoCategoryServiceImpl extends SimpleServiceImpl<VideoCategoryMapper, VideoCategory> implements VideoCategoryService {
	@Resource
	private VideoService videoService;
	
	@Transactional(rollbackFor = { Exception.class })
	@Override
	public void insertIfPermission(VideoCategory record) throws Exception {
		baseMapper.insert(record);
		
		VideoCategory entity = new VideoCategory();
		entity.setCode(record.getCode());
		if(selectCount(entity) > 1){
			throw new ResultCodeException("分类编号已经存在！");
		}
	}
	
	@Transactional(rollbackFor = { Exception.class })
	@Override
	public void updateIfPermission(VideoCategory record) throws Exception {
		baseMapper.updateById(record);

		VideoCategory entity = new VideoCategory();
		entity.setCode(record.getCode());
		if (selectCount(entity) > 1) {
			throw new ResultCodeException("分类编号已存在！");
		}
	}

	@Override
	public ResultCode deleteIfPermision(Long id) {
		VideoCategory entity = new VideoCategory();
		entity.setParentId(id);
		if (selectCount(entity) > 0) {
			return BizResultCode.error("分类下有子分类，不能删除！");
		}
		
		Video video = new Video();
		video.setVideoCategoryId(id);
		if(videoService.selectCount(video) > 0){
			return BizResultCode.error("分类下有视频，不能删除！");
		}
		
		baseMapper.deleteById(id);
		
		return BizResultCode.success();
	}
	
	@Override
	public VideoCategoryAdminVO selectOneAdminVO(Long id) {
		return baseMapper.selectOneAdminVO(id);
	}
	
	@Override
	public List<VideoCategoryAdminVO> selectAdminVO() {
		return baseMapper.selectAdminVO();
	}
}
